package com.example.administrator.dagger2demo.ui.login;

import android.os.Environment;
import android.util.Log;

import com.example.administrator.dagger2demo.application.DemoApplication;
import com.example.administrator.dagger2demo.http.RestApi;
import com.example.administrator.dagger2demo.domain.ReleaseInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.inject.Inject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13.
 */
public class LoginPresenter implements LoginContract.LoginActionsListener {

    private final RestApi _restApi;
    private final LoginContract.View mview;

    @Inject
    public LoginPresenter(RestApi restApi, LoginContract.View view) {
        Log.i("TAG", "进入了...IndexPresenter");
        this._restApi = restApi;
        Log.i("TAG",_restApi==null?"进入了...is null":"进入了...not null");
        this.mview = view;
        Log.i("TAG",mview==null?"进入了...is null":"进入了...not null");
    }

    @Override
    public void login(String u, String p) {
        Log.i("TAG",_restApi==null?"_restApi==null":"_restApi!=null");
        Call<ResponseBody> call =   _restApi.downloadFileWithFixedUrl();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.i("TAG", "onResponse");
                ResponseBody  body = response.body();
                File futureStudioIconFile = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath() +"/new-ca2fedc5f82942d8c2b66157be866e6c.apatch");
                try {
                    // todo change the file location/name according to your needs
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        byte[] fileReader = new byte[4096];
                        long fileSize = body.contentLength();
                        long fileSizeDownloaded = 0;
                        inputStream = body.byteStream();
                        outputStream = new FileOutputStream(futureStudioIconFile);
                        while (true) {
                            int read = inputStream.read(fileReader);
                            if (read == -1) {
                                break;
                            }
                            outputStream.write(fileReader, 0, read);
                            fileSizeDownloaded += read;
                            Log.i("TAG", "file download: " + fileSizeDownloaded + " of " + fileSize);
                        }
                        DemoApplication.mPatchManager.addPatch(futureStudioIconFile.getAbsolutePath());
                        if (futureStudioIconFile.exists()) {
                            boolean result = futureStudioIconFile.delete();
                            if (!result)
                                Log.i("TAG", futureStudioIconFile.getAbsolutePath() + " delete fail");
                        }
                        outputStream.flush();
                    } catch (IOException e) {
                        Log.i("TAG",e.toString());
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    }
                } catch (IOException e) {
                    Log.i("TAG", e.toString());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i("TAG", "onFailure");
            }
        });


    }

    @Override
    public void loginSuccess(String message) {
        Observable<ArrayList<ReleaseInfo>> observable =  _restApi.requestIndex();

        observable
                .subscribeOn(Schedulers.io())//订阅调度在io流线程
                .observeOn(AndroidSchedulers.mainThread())//观察调度主线程
                .subscribe(new Observer<ArrayList<ReleaseInfo>>() {//订阅
                    @Override
                    public void onCompleted() {
                        Log.i("TAG","onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("TAG","onError="+e.toString());
//                       Retrofit  _retrofit =  DemoApplication.getAppComponent().getrRetrofit();
                        Log.i("TAG",_restApi==null?"_retrofit==null":"_retrofit!=null");
//                        ApiException exception = ApiException.create(e, _retrofit);
                    }

                    @Override
                    public void onNext(ArrayList<ReleaseInfo> releaseInfos) {
                        Log.i("TAG","onNext="+releaseInfos.size());
                    }
                });

    }

    @Override
    public void loginError(String message) {

    }

}
